package com.currency.mall.ui.my.recharge;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.currency.mall.Constant;
import com.currency.mall.R;
import com.currency.mall.entity.RechargeBean;
import com.currency.mall.event.OrderEvent;
import com.currency.mall.netWork.NetWork;
import com.currency.mall.util.TimeUtil;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.commonbase.util.Tools;
import com.mifengs.commonbase.widget.PopBottomSelectView;
import com.mifengs.commonbusines.entity.ResponseBean;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/12/25.
 */

public class RechargeDetailsActivity extends BaseActivity {

    @BindView(R.id.ll_bandcard)
    LinearLayout llBandcard;
    @BindView(R.id.ll_alipay)
    LinearLayout llAlipay;
    @BindView(R.id.iv_recharge_type)
    ImageView ivRechargeType;
    @BindView(R.id.tv_recharge_type_name)
    TextView tvRechargeTypeName;
    @BindView(R.id.tv_count_down)
    TextView tvCountDown;
    @BindView(R.id.tv_recharge_price)
    TextView tvRechargePrice;
    @BindView(R.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R.id.tv_bank_address)
    TextView tvBankAddress;
    @BindView(R.id.tv_bank_receivables_name)
    TextView tvBankReceivablesName;
    @BindView(R.id.tv_bankcar_num)
    TextView tvBankcarNum;
    @BindView(R.id.tv_bank_label)
    TextView tvBankLabel;
    @BindView(R.id.tv_ailpay_receivables_name)
    TextView tvAilpayReceivablesName;
    @BindView(R.id.tv_ailpay_account_num)
    TextView tvAilpayAccountNum;
    @BindView(R.id.tv_alipay_label)
    TextView tvAlipayLabel;
    private String[] mSelectStrings = new String[]{"银行卡", "支付宝"};
    private MyTime myTime;
    private int type;//0是银行卡 1是支付宝
    private RechargeBean.BankBean bankInfo;
    private RechargeBean.RechargeInfo rechargeInfo;
    private RechargeBean.AlipayBean alipayInfo;
    private String rechargePrice;
    private String payType;
    private Dialog rechargeDilaog;
    private Dialog hintDialogShow;
    private int timeOut;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge_details);
        ButterKnife.bind(this);
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(getContext(), R.color.title_color));
        StatusBarUtils.StatusBarLightMode(this);
        type = getIntent().getIntExtra("type", 0);
        bankInfo = (RechargeBean.BankBean) getIntent().getSerializableExtra("bankInfo");
        rechargeInfo = (RechargeBean.RechargeInfo) getIntent().getSerializableExtra("rechargeInfo");
        alipayInfo = (RechargeBean.AlipayBean) getIntent().getSerializableExtra("alipayInfo");
        rechargePrice = getIntent().getStringExtra("price");
        timeOut = getIntent().getIntExtra("timeOut", 0);
        init();
    }

    private void init() {
        setView();
        myTime = new MyTime(timeOut, 1000);
        myTime.start();
        if (type == 0) {
            updateView(0);
        } else {
            updateView(1);
        }
    }

    private void setView() {
        tvRechargePrice.setText("¥ " + rechargePrice);
        //银行卡
        tvBankName.setText(bankInfo.getBank_name());
        tvBankAddress.setText(bankInfo.getBank_address());
        tvBankReceivablesName.setText(bankInfo.getBank_real_name());
        tvBankcarNum.setText(bankInfo.getBank_code());
        tvBankLabel.setText(rechargeInfo.getRecharRemark());
        //支付宝
        tvAilpayReceivablesName.setText(alipayInfo.getPayment());
        tvAilpayAccountNum.setText(alipayInfo.getAlipay_account());
        tvAlipayLabel.setText(rechargeInfo.getRecharRemark());

    }


    public void initSelectView() {
        final PopBottomSelectView popBottomSelectView = new PopBottomSelectView(this);
        popBottomSelectView.setSelectData(mSelectStrings);
        popBottomSelectView.setItemOnClick(new PopBottomSelectView.OnSelectItemClickListener() {
            @Override
            public void onItemClick(int position) {
                switch (position) {
                    case 0:
                        updateView(0);
                        break;
                    case 1:
                        updateView(1);
                        break;

                }
                popBottomSelectView.dismiss();
            }
        });
        popBottomSelectView.show();
    }

    private void updateView(int postion) {
        if (postion == 0) {
            payType ="BANK";
            llBandcard.setVisibility(View.VISIBLE);
            llAlipay.setVisibility(View.GONE);
            ivRechargeType.setBackgroundResource(R.drawable.bankcard_default);
            tvRechargeTypeName.setText("银行卡");
        } else {
            payType ="ALIPAY";
            llBandcard.setVisibility(View.GONE);
            llAlipay.setVisibility(View.VISIBLE);
            ivRechargeType.setBackgroundResource(R.drawable.alipay_default);
            tvRechargeTypeName.setText("支付宝");
        }
    }

    private void hintDialogShow() {
        hintDialogShow = new Dialog(getContext(), R.style.dialog);
        hintDialogShow.setContentView(R.layout.dialog_not_title);
        hintDialogShow.show();
        hintDialogShow.setCancelable(false);
        View view = (View)hintDialogShow.findViewById(R.id.v_view);
        TextView tvInfo = (TextView) hintDialogShow.findViewById(R.id.tv_info);
        tvInfo.setText("重要提醒：请在付款信息中备注付款参考号");
        Button okBtn = hintDialogShow.findViewById(R.id.bt_ok);
        view.setVisibility(View.GONE);
        okBtn.setVisibility(View.GONE);
        Button cancleBtn = hintDialogShow.findViewById(R.id.bt_cancle);
        cancleBtn.setText("知道了");
        cancleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hintDialogShow.dismiss();
            }
        });
    }


    @OnClick({R.id.ll_back, R.id.rl_recharge_type, R.id.iv_bank_hint, R.id.iv_qrcode, R.id.iv_alipay_hint, R.id.tv_cancle_order, R.id.rl_complete,R.id.iv_bank_copy_payee, R.id.iv_copy_bank_account, R.id.iv_copy_bank_label, R.id.iv_alipay_copy_payee, R.id.iv_alipay_copy_account, R.id.tv_alipay_label})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_bank_hint:
                hintDialogShow();
                break;
            case R.id.iv_qrcode:
                break;
            case R.id.iv_alipay_hint:
                hintDialogShow();
                break;
            case R.id.tv_cancle_order:
                rechargeOrderDilaogShow(0);
                break;
            case R.id.rl_complete:
                rechargeOrderDilaogShow(1);
                break;
            case R.id.ll_back:
                finish();
                break;
            case R.id.rl_recharge_type:
                initSelectView();
                break;
            case R.id.iv_bank_copy_payee:
                copyValue("收款人： ",bankInfo.getBank_real_name());
                break;
            case R.id.iv_copy_bank_account:
                copyValue("银行卡账号： ",bankInfo.getBank_code());
                break;
            case R.id.iv_copy_bank_label:
                copyValue("参考号： ",rechargeInfo.getRecharRemark());
                break;
            case R.id.iv_alipay_copy_payee:
                copyValue("收款人： ",alipayInfo.getPayment());
                break;
            case R.id.iv_alipay_copy_account:
                copyValue("支付宝账号： ",alipayInfo.getAlipay_account());
                break;
            case R.id.tv_alipay_label:
                copyValue("参考号： ",rechargeInfo.getRecharRemark());
                break;
        }
    }
    private void copyValue(String name,String value){
        Tools.copy(value,getContext());
        ToastUitl.show(name+value+"    复制成功",200);
    }

    class MyTime extends CountDownTimer {

        public MyTime(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            Date date = new Date(millisUntilFinished);
            SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
            tvCountDown.setText(TimeUtil.getCountTimeByLong(millisUntilFinished) + "");
        }

        @Override
        public void onFinish() {
            tvCountDown.setText("00:00");
            sumbitRechargeState("PAY_CANCEL");
        }
    }


    public void sumbitRechargeState(final String payState) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", rechargeInfo.getId());
        hashMap.put("payType", payType);
        hashMap.put("payState", payState);
        NetWork.getUserApi().rechargeState(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseBean responseBean) {
                        if (responseBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            if("PAY_CANCEL".equals(payState)){
//                                ToastUitl.show("充值订单已取消", 200);
//                                EventBus.getDefault().post(new OrderEvent(OrderEvent.ORDER_RECHARGE_STATU, 2));
                                toRechargeDetail(2);
                            }else{
//                                ToastUitl.show("已经付款成功，请等待后台确认到账", 200);
//                                EventBus.getDefault().post(new OrderEvent(OrderEvent.ORDER_RECHARGE_STATU, 0));
                                toRechargeDetail(0);
                            }
                            finish();

                        } else {
                            ToastUitl.show(responseBean.getMsg(), 200);
                        }
                    }
                });
    }

    private void toRechargeDetail(int type){
       Intent intent = new Intent(getContext(), WaitConfirmActivity.class);
        intent.putExtra("rechargeInfo", rechargeInfo);
        intent.putExtra("price", rechargePrice);
        intent.putExtra("type", type);
       if( "BANK".equals(payType)){
           intent.putExtra("status", 0);
       }else{
           intent.putExtra("status", 1);
       }
       startActivity(intent);

    }

    private void rechargeOrderDilaogShow(final int type) {
        rechargeDilaog = new Dialog(getContext(), R.style.dialog);
        rechargeDilaog.setContentView(R.layout.dialog_not_title);
        rechargeDilaog.show();
        rechargeDilaog.setCancelable(false);
        TextView tvInfo = (TextView) rechargeDilaog.findViewById(R.id.tv_info);
        if(type == 0){
            tvInfo.setText("每个用户每天只能取消10笔订单，请谨慎操作");
        }else{
            tvInfo.setText("请确定已经付款成功，请勿恶意点击付款，否则有可能造成资金损失");
        }

        Button okBtn = rechargeDilaog.findViewById(R.id.bt_ok);
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if( type == 0){
                    sumbitRechargeState("PAY_CANCEL");
                }else{
                    sumbitRechargeState("PAY_OPERATION");
                }
                rechargeDilaog.dismiss();

            }
        });
        Button cancleBtn = rechargeDilaog.findViewById(R.id.bt_cancle);
        cancleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rechargeDilaog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myTime != null) {
            myTime.cancel();
        }
    }
}
